package com.nervenets.general.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class MenuRole implements Serializable {
    @ApiModelProperty(value = "ID")
    private String id;
    @ApiModelProperty(value = "名称")
    private String name;
    @ApiModelProperty(value = "标识")
    private String code;
    @ApiModelProperty(value = "下级")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<MenuRole> children;
    @ApiModelProperty(value = "标签")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String[] tags;
    @ApiModelProperty(value = "路由")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String router;
    @ApiModelProperty(value = "组件")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String component;
    @ApiModelProperty(value = "权限代码")
    private String permission;
    @ApiModelProperty(value = "排序")
    @JsonIgnore
    private int queue;

    public MenuRole(String id, String name, String code, String[] tags, String router, String component, String permission, int queue) {
        this.id = id;
        this.name = name;
        this.code = code;
        this.tags = tags;
        this.router = router;
        this.component = component;
        this.permission = permission;
        this.queue = queue;
    }

    public MenuRole add(MenuRole menu) {
        if (null == this.children) this.children = new ArrayList<>();
        this.children.add(menu);
        this.children.sort(Comparator.comparingInt(MenuRole::getQueue));
        return this;
    }

    public boolean contains(MenuRole menu) {
        if (null == this.children) return false;
        return this.children.contains(menu);
    }

    @JsonIgnore
    public List<String> getAllMenuIds() {
        List<String> ids = new ArrayList<>();
        ids.add(this.id);
        if (null != this.children) {
            for (MenuRole child : this.children) {
                ids.addAll(child.getAllMenuIds());
            }
        }
        return ids;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MenuRole menuRole = (MenuRole) o;
        return id.equals(menuRole.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
